#include "doublelist.h"
#include "staffManage.h"

//创建一个双向循环链表的头节点
dlist_t create_doublelist(void)
{
	dlist_t h = (dlist_t)malloc(sizeof(dnode_t));
	h->next = h;
	h->prior = h;
	return h;
}

//双向循环链表插入
int insert_head_doublelist(dlist_t h,void* data)
{
	dlist_t new;
	dlist_t np = h->next; //头节点的下一个节点

	new = (dlist_t)malloc(sizeof(dnode_t));
	new->data = data;
	
	new->prior = h;
	new->next = np;

	h->next = new;
	np->prior = new;

	return 0;
}

int is_empty_doublelist(dlist_t h)
{
	return h->next == h;
}

//32位系统中
int cmp_void(void* xa,void* xb,int size_num)
{

	if(size_num == 1)
	{
		return *(char*)xa - *(char*)xb ;
	}else if(size_num == 2)
	{
		return *(short*)xa - *(short*)xb ;
	}else if(size_num == 4)
	{
		return *(int *)xa - *(int *)xb ;
	}else if(size_num == 8)
	{
		return *(double *)xa - *(double *)xb ;
	}else{
		return *(int *)xa - *(int *)xb ;
	}
	return -2;
}

/**
 * 从链表中删除一个数据
 * h 链表头
 * x 需要删除数据域指针
 * num 数据长度 可用sizeof获取
 */
void* delete_doublelist(dlist_t h,void *x,int size_num)
{
	if(x == NULL)
	{
		return NULL;
	}
	if(is_empty_doublelist(h)){
		return NULL;
	}
	
	dlist_t temp = h->next;
	while(cmp_void(temp->data,x,size_num) != 0)
	{
		temp=temp->next;
		if(temp == h){
			printf("删除失败\n");
			return NULL;
		}
	}

	printf("删除成功！\n");
	
	dlist_t np = temp->next;
	np->prior = temp->prior;
	np->prior->next = np; 
	
	free(temp);
	temp = NULL;
	
	return x;
}






